package no.ntnu.item.ttm4115.termproject.groupchatagent.gui;

/****************************************************************/
/*                      GroupChatGUI	                            */
/*                                                              */
/****************************************************************/
import java.awt.*;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.swing.*;
import no.ntnu.item.ttm4115.termproject.ChatMessage;
import no.ntnu.item.ttm4115.termproject.InitiateIMFromGUI;
import no.ntnu.item.ttm4115.termproject.ReleasePlayerGroupChatAgent;
import no.ntnu.item.ttm4115.termproject.playeragent.gui.MeetingPlaceGUI;
import no.tellu.common.actorframe.ActorSM;
import no.tellu.common.javaframe.ActorAddress;


/**
 *@author Kim A Martinsen
 *GroupChatGUI
 *
 */
public class GroupChatGUI extends JPanel
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	// Variables declaration
	@SuppressWarnings("unused")
	private javax.swing.JPanel jPanelGroupChat;
    private javax.swing.JLabel jLabelGrpCht;
    private javax.swing.JLabel jLabelGrpChtInput;
	private javax.swing.JScrollPane jScrollPaneGrpChtInput;
    private javax.swing.JScrollPane jScrollPaneGrpChtOutput;
    private javax.swing.JScrollPane jScrollPanelGrpChatOnline;
    private javax.swing.JTextArea jTextAreaGrpChtInput;
    private javax.swing.JList jListGrpChtOnline;
    private javax.swing.JList jListGrpChtOutput;
    private javax.swing.JButton closeButtonGrpCht;
    private javax.swing.JButton sendButtonGrpCht;
	private String playerName;
	private String groupName;
	private ActorAddress groupChatAgentGroup;
	private ActorSM asm;
	private MeetingPlaceGUI mainFrame;
	private final static String newline = "\n";
	private DefaultListModel grpChtOnlineModel;
	private DefaultListModel grpChtOutputModel;
	{
		//Set Look & Feel
		try {
			javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	// End of variables declaration
	

	public GroupChatGUI(String playerName, ActorAddress groupChatAgentGroup, ActorSM asm, MeetingPlaceGUI mainFrame, String groupName)
	{
		super();
		this.playerName = playerName;
		this.groupName = groupName;
		this.groupChatAgentGroup = groupChatAgentGroup;
		this.asm = asm;
		this.mainFrame = mainFrame;
		this.mainFrame.getPane().addTab(this.groupName+" Chat", this);
		this.repaint();
		this.mainFrame.repaint();
		
		initComponents();
	}
	
		public void initComponents(){
		
		jPanelGroupChat = new javax.swing.JPanel();
        jScrollPanelGrpChatOnline = new javax.swing.JScrollPane();
        jListGrpChtOnline = new javax.swing.JList();
        jScrollPaneGrpChtOutput = new javax.swing.JScrollPane();
        jListGrpChtOutput = new javax.swing.JList();
        jScrollPaneGrpChtInput = new javax.swing.JScrollPane();
        jTextAreaGrpChtInput = new javax.swing.JTextArea();
        sendButtonGrpCht = new javax.swing.JButton();
        closeButtonGrpCht = new javax.swing.JButton();
        jLabelGrpCht = new javax.swing.JLabel();
        jLabelGrpChtInput = new javax.swing.JLabel();
		grpChtOnlineModel = new DefaultListModel();
		grpChtOutputModel = new DefaultListModel();
        
        jLabelGrpCht.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabelGrpCht.setText("Group Chat for:");

        jLabelGrpChtInput.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabelGrpChtInput.setText("N/A");
		
        jListGrpChtOnline.setModel(getJListGrpChtOnlineModel());
        jListGrpChtOnline.addMouseListener(
				new MouseAdapter() {
					public void mouseReleased( MouseEvent e ) {
						if ( e.isPopupTrigger()) {
							popupToGrpChtPlayerList().show( (JComponent)e.getSource(), e.getX(), e.getY() );
						}
					}
				}
		);
        jScrollPanelGrpChatOnline.setViewportView(jListGrpChtOnline);
      
        jListGrpChtOutput.setModel(getJListGrpChtOuputModel());
        jListGrpChtOutput.setCellRenderer(new MyGroupChatCellRenderer());
        jScrollPaneGrpChtOutput.setViewportView(jListGrpChtOutput);

        jTextAreaGrpChtInput.setColumns(20);
        jTextAreaGrpChtInput.setRows(5);
        jScrollPaneGrpChtInput.setViewportView(jTextAreaGrpChtInput);

        sendButtonGrpCht.setIcon(new javax.swing.ImageIcon(getClass().getResource("001_13.png"))); // NOI18N
        sendButtonGrpCht.setText("Send");
        sendButtonGrpCht.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e)
			{
				sendButtonGrpCht_actionPerformed(e);
			}

		});

        closeButtonGrpCht.setIcon(new javax.swing.ImageIcon(getClass().getResource("001_05.png"))); // NOI18N
        closeButtonGrpCht.setText("Close");
		closeButtonGrpCht.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e)
			{
				closeButtonGrpCht_actionPerformed(e);
			}

		});

        javax.swing.GroupLayout jPanelGroupChatLayout = new javax.swing.GroupLayout(this);
        this.setLayout(jPanelGroupChatLayout);
        jPanelGroupChatLayout.setHorizontalGroup(
            jPanelGroupChatLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelGroupChatLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanelGroupChatLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanelGroupChatLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(jPanelGroupChatLayout.createSequentialGroup()
                            .addComponent(jScrollPaneGrpChtInput, javax.swing.GroupLayout.PREFERRED_SIZE, 423, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(jPanelGroupChatLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(closeButtonGrpCht, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(sendButtonGrpCht, javax.swing.GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE)))
                        .addGroup(jPanelGroupChatLayout.createSequentialGroup()
                            .addComponent(jScrollPanelGrpChatOnline, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jScrollPaneGrpChtOutput)))
                    .addGroup(jPanelGroupChatLayout.createSequentialGroup()
                        .addComponent(jLabelGrpCht)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabelGrpChtInput, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(25, Short.MAX_VALUE))
        );
        jPanelGroupChatLayout.setVerticalGroup(
            jPanelGroupChatLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelGroupChatLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanelGroupChatLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelGrpCht)
                    .addComponent(jLabelGrpChtInput))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanelGroupChatLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPanelGrpChatOnline, javax.swing.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE)
                    .addComponent(jScrollPaneGrpChtOutput, javax.swing.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanelGroupChatLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanelGroupChatLayout.createSequentialGroup()
                        .addGap(44, 44, 44)
                        .addComponent(sendButtonGrpCht)
                        .addGap(18, 18, 18)
                        .addComponent(closeButtonGrpCht))
                    .addGroup(jPanelGroupChatLayout.createSequentialGroup()
                        .addGap(27, 27, 27)
                        .addComponent(jScrollPaneGrpChtInput, javax.swing.GroupLayout.DEFAULT_SIZE, 133, Short.MAX_VALUE)))
                .addContainerGap())
        );
        
        
	}
	
	/** Add Component Without a Layout Manager (Absolute Positioning) */
	@SuppressWarnings("unused")
	private void addComponent(Container container,Component c,int x,int y,int width,int height)
	{
		c.setBounds(x,y,width,height);
		container.add(c);
	}

	

	private void sendButtonGrpCht_actionPerformed(ActionEvent e)
	{
		ChatMessage cm = new ChatMessage(getPlayerName()+ ": "+jTextAreaGrpChtInput.getText().toString());
		asm.sendMessage(cm, this.groupChatAgentGroup);
		jTextAreaGrpChtInput.setText("");

		
		

	}

	private void closeButtonGrpCht_actionPerformed(ActionEvent e)
	{
		JDialog.setDefaultLookAndFeelDecorated(true);
        int response = JOptionPane.showConfirmDialog(null, "Do you really wanna close?"+newline+"If you return, you will only see the 3 latest messages", "Confirm close",
            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (response == JOptionPane.NO_OPTION) {
          
        } else if (response == JOptionPane.YES_OPTION) {
        	asm.sendMessage(new ReleasePlayerGroupChatAgent(getPlayerName()), this.groupChatAgentGroup);
    		asm.sendMessage(new ReleasePlayerGroupChatAgent(getPlayerName()), asm.getContext().getParentAddress());
        	mainFrame.getPane().removeTabAt(mainFrame.getPane().getSelectedIndex());
          
        } else if (response == JOptionPane.CLOSED_OPTION) {
        	
        }
	    
		
	}
	
	
	public void receiveChatMsg(String message){
		 
		sendButtonGrpCht.setEnabled(true);
		jTextAreaGrpChtInput.setEditable(true);
		GrChtListItem li = new GrChtListItem(Color.black, message);
        getJListGrpChtOuputModel().addElement(li);
        this.repaint();
        Date date = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
		String time = formatter.format(date);
        mainFrame.updateActivityList(time+ ": "+groupName+" chat is updated", "Chat");
	}

	public void groupChatStartup(){
		 		
		GrChtListItem li = new GrChtListItem(Color.darkGray, "*************************************");
        getJListGrpChtOuputModel().addElement(li);	
        GrChtListItem li2 = new GrChtListItem(Color.darkGray, "Welcome to TreasureHunt GroupChat");
        getJListGrpChtOuputModel().addElement(li2);
        GrChtListItem li3 = new GrChtListItem(Color.darkGray, "You are the first one to join");
        getJListGrpChtOuputModel().addElement(li3);
        GrChtListItem li4 = new GrChtListItem(Color.darkGray, " ");
        getJListGrpChtOuputModel().addElement(li4);
        GrChtListItem li5 = new GrChtListItem(Color.darkGray, "*************************************");
        getJListGrpChtOuputModel().addElement(li5);
        GrChtListItem li6 = new GrChtListItem(Color.darkGray, " ");
        getJListGrpChtOuputModel().addElement(li6);
	}
	
	public void informOthersOfNewPlayer(String playerName) {
		GrChtListItem li = new GrChtListItem(Color.darkGray, "**"+playerName+" has joined the chat");
        getJListGrpChtOuputModel().addElement(li);
	}

	@SuppressWarnings("unchecked")
	public void setPreviouslySaid(HashMap previousMessages){
		
		GrChtListItem li = new GrChtListItem(Color.darkGray, "*************************************");
        getJListGrpChtOuputModel().addElement(li);	
        GrChtListItem li2 = new GrChtListItem(Color.darkGray, "Welcome to TreasureHunt GroupChat");
        getJListGrpChtOuputModel().addElement(li2);
        GrChtListItem li3 = new GrChtListItem(Color.darkGray, " ");
        getJListGrpChtOuputModel().addElement(li3);
        GrChtListItem li4 = new GrChtListItem(Color.darkGray, "*************************************");
        getJListGrpChtOuputModel().addElement(li4);
        GrChtListItem li5 = new GrChtListItem(Color.darkGray, " ");
        getJListGrpChtOuputModel().addElement(li5);

		Iterator<Map.Entry> iterator = previousMessages.entrySet().iterator();
		
		while(iterator.hasNext()){
			Map.Entry me = (Map.Entry)iterator.next();
			
	        GrChtListItem li6 = new GrChtListItem(Color.darkGray, "**"+me.getValue().toString()+ " ");
	        getJListGrpChtOuputModel().addElement(li6);
			
		}
		GrChtListItem li7 = new GrChtListItem(Color.darkGray, " ");
        getJListGrpChtOuputModel().addElement(li7);
	}

	@SuppressWarnings("unchecked")
	public void appendChattersToList(HashMap usersChatting){
		
		getJListGrpChtOnlineModel().removeAllElements();
		Iterator<Map.Entry> iterator = usersChatting.entrySet().iterator();
		
		while(iterator.hasNext()){
			Map.Entry me = (Map.Entry)iterator.next();
			getJListGrpChtOnlineModel().addElement(me.getKey());
			
		
			
		}
	}
	
	public void appendMeToList (){
		getJListGrpChtOnlineModel().addElement(getPlayerName());
	}
	
	@SuppressWarnings("unchecked")
	public void removePlayerFromList(String name, HashMap usersChatting){
		
		getJListGrpChtOnlineModel().removeAllElements();
		GrChtListItem li = new GrChtListItem(Color.darkGray, "**"+name+" has left the chat");
        getJListGrpChtOuputModel().addElement(li);
		Iterator<Map.Entry> iterator = usersChatting.entrySet().iterator();
		
		while(iterator.hasNext()){
			Map.Entry me = (Map.Entry)iterator.next();
			getJListGrpChtOnlineModel().addElement(me.getKey());
		}
	}
	
	public DefaultListModel getJListGrpChtOuputModel(){
    	return grpChtOutputModel;
    }
	
	public DefaultListModel getJListGrpChtOnlineModel(){
    	return grpChtOnlineModel;
    }
	
	public String getPlayerName(){
		return this.playerName;
	}

	public void setjLabelGrpChtInput(String groupName){
		jLabelGrpChtInput.setText(groupName);
	}
	/**
	 * 
	 */
	public void showIMWindow(){
		String imName = jListGrpChtOnline.getSelectedValue().toString(); 
		asm.sendMessage(new InitiateIMFromGUI(mainFrame, imName), asm.getContext().getParentAddress());
	}
	
	
	 /**
     * 
     * Popup to onlinePlayersList
     */
    private JPopupMenu popupToGrpChtPlayerList(){

		JPopupMenu popup;
		JMenuItem mi;
		
		popup = new JPopupMenu();
		mi = new JMenuItem("Activity History");
		mi.addActionListener(new PopupListener());
		mi.setActionCommand("gethistory");
		popup.add(mi);
			
		mi = new JMenuItem("IM Player");
		mi.addActionListener(new PopupListener());
		mi.setActionCommand("implayer");
		popup.add(mi);
		
		popup.setOpaque(true);
		popup.setLightWeightPopupEnabled(true);
		return popup;
    }

    
    class PopupListener implements ActionListener {
    	public void actionPerformed(ActionEvent e) {
    		if(e.getActionCommand().endsWith("gethistory")){

    		}

    		if(e.getActionCommand().endsWith("implayer")){
    			showIMWindow();
    		}
    		
    	}
    		
    }
    
}

class MyGroupChatCellRenderer extends 
JLabel implements ListCellRenderer {

    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public MyGroupChatCellRenderer () {
    // Don't paint behind the component
    	setBackground(Color.white);
        setOpaque(true);
        
    }

// Set the attributes of the 
//class and return a reference
public Component getListCellRendererComponent(JList list,
      Object value, // value to display
      int index,    // cell index
      boolean iss,  // is selected
      boolean chf)  // cell has focus?
{

    setText(((GrChtListItem)value).getValue());
    setForeground(((GrChtListItem)value).getColor());


           return this;
      }
   }


    
 

